import { Component, OnInit } from '@angular/core';
import { RunStopsService } from "../../../../../service/run-stops.service";
import { RunStop } from "../../../../../entity/run-stop.model";
import { BladeContainerBase } from "../../../../../shared/blade/blade-container-base";
import { BladeData } from "../../../../../shared/blade/blade-data";
import { Blade } from "../../../../../shared/blade/blade.model";
import { Command } from "../../../../../shared/toolbar.service";
import { DialogResult } from "../../../../../shared/dialog.service";
import { Scheme } from "../../../../../entity/scheme.model";
import { TagMapEditComponent } from "../tag-map-edit/tag-map-edit.component"
import { TagMapService } from "../../../../../service/tag-map.service"
import { TagMap } from '../../../../../entity/tag-map.model';
import { MatrixStateGroup } from "../../../../../entity/matrix-state-group.model";
import { MatrixLogicGroup } from "../../../../../entity/matrix-logic-group.model";
import { Tag } from "../../../../../entity/tag.model";
import { TagService } from "../../../../../service/tag.service";
import { MatrixStateGroupService } from "../../../../../service/matrix-state-group.service";
import { MatrixLogicGroupService } from "../../../../../service/matrix-logic-group.service";
interface DataSet {
  current: Scheme,
  tags: Tag[],
  tagMaps: TagMap[],
  mlGroups: MatrixLogicGroup[];
  msGroups: MatrixStateGroup[];
}
@Component({
  selector: 'app-tag-map-list',
  templateUrl: './tag-map-list.component.html',
  styleUrls: ['./tag-map-list.component.css']
})
export class TagMapListComponent extends BladeContainerBase<Scheme>{

  /**
   * 测点映射集合
   * 
   * @type {TagMap[]}
   * @memberof TagMapListComponent
   */
  tagMaps: TagMap[] = [];
  original: TagMap[] = [];
  /**
   * 当前测点映射信息
   * 
   * @type {TagMap}
   * @memberof TagMapListComponent
   */
  currentTagMap: TagMap;

  /**
   * 测点集合
   * 
   * @type {Tag[]}
   * @memberof TagMapListComponent
   */
  tags: Tag[];

  /**
   * 矩阵逻辑组数据集合
   * 
   * @type {MatrixLogicGroup[]}
   * @memberof TagMapListComponent
   */
  mlGroups: MatrixLogicGroup[];

  /**
   * 矩阵状态组数据集合
   * 
   * @type {MatrixStateGroup[]}
   * @memberof TagMapListComponent
   */
  msGroups: MatrixStateGroup[];
  isAllChecked: boolean = false;
  isFaultTagChecked: boolean = false;
  isTagStateMarkChecked: boolean = false;
  sreachValue: string = "";
  constructor(
    private tagMapService: TagMapService,
    private tagService: TagService,
    private mlgService: MatrixLogicGroupService,
    private msgService: MatrixStateGroupService
  ) {
    super()
  }

  ngOnInit() {
    this.commands = [
      new Command("add", "添加", "fa fa-plus", "setofkey:insert", blade => this.exeAdd(blade), blade => this.canExeAdd(blade)),
      new Command("edit", "编辑", "fa fa-edit", "setofkey:update", blade => this.exeEdit(blade), blade => this.canExeEdit(blade)),
      new Command("delete", "删除", "fa fa-trash-o", "setofkey:delete", blade => this.exeDelete(blade), blade => this.canDelete(blade)),
    ];
    let getMLGroups = this.mlgService.getMatrixLogicGroups();
    let getMSGroups = this.msgService.getMatrixStateGroups();
    let getTags = this.tagService.getTagList();
    Promise.all([getMLGroups, getMSGroups, getTags])
      .then(res => {
        if (res[0]) {
          this.mlGroups = [...res[0]];
        };
        if (res[1]) {
          this.msGroups = [...res[1]];
        };
        if (res[1]) {
          this.tags = [...res[2]];
          this.tags.forEach(v => {
            v.tagName = v.tagDesc ? v.tagDesc + '-' + v.tagCode : v.tagName + '-' + v.tagCode;
          });
        };

      })
    super.ngOnInit();

  }
  initData(): any {
    this.tagMapService.getFaultsBySchemeId(this.currentEntity.schemeId)
      .then(res => {
        this.bladeData.isLoading = false;
        if (res) {
          this.original = [...res];
          this.onSearchTagName(this.sreachValue);
        }
      })
      .catch(err => {
        console.log(err);
      })
  }
  exeAdd(blend: Blade): void {
    let data: BladeData = new BladeData();
    data.id = "modelGroupingCreate";
    data.title = "创建一个测点信息";
    data.isClosingDisabled = false;
    let newTagMap: TagMap = {
      tagMapId: 0,
      schemeId: this.currentEntity.schemeId,
      faultTag: false,
      isChecked: false,
    };
    let dataSet: DataSet = {
      current: this.currentEntity,
      tags: this.tags,
      tagMaps: this.tagMaps,
      mlGroups: this.mlGroups,
      msGroups: this.msGroups
    }
    let createKeyBlade = this.bladeService.createBlade(TagMapEditComponent, data, true, newTagMap, dataSet);
    this.bladeService.showBlade(createKeyBlade, this.currentBlade);
  }
  canExeAdd(blend: Blade): boolean {
    return true;
  }
  exeEdit(blend: Blade): void {
    if (this.currentEntity != undefined) {
      let data: BladeData = new BladeData();
      data.id = "standardCurveEdit";
      data.title = "编辑测点信息";
      let dataSet: DataSet = {
        current: this.currentEntity,
        tags: this.tags,
        tagMaps: this.tagMaps,
        mlGroups: this.mlGroups,
        msGroups: this.msGroups
      }
      let editKeyBlade = this.bladeService.createBlade(TagMapEditComponent, data, false, this.currentTagMap, dataSet);
      this.currentBlade.bladeService.showBlade(editKeyBlade, this.currentBlade);

    }
  }
  canExeEdit(blend?: Blade): boolean {
    return this.currentTagMap != null;
  }
  exeDelete(blend: Blade): void {
    let selectedKeys = this.getSelected();
    if (selectedKeys.length > 0) {
      this.dialogService
        .showConfirmationDialog("确认删除", "是否要删除选中项？")
        .subscribe(dialogResult => {
          if (dialogResult == DialogResult.Ok) {
            this.currentBlade.bladeData.isLoading = true;
            this.tagMapService.batchDelete(selectedKeys.map(o => o.tagMapId))
              .then(res => {
                if (res) {
                  super.refresh(this.currentEntity);
                }
              })
              .catch(error => this.bladeData.error = error)
              .then(res => this.bladeData.isLoading = false);
          }
        })
    }
  }
  canDelete(blend?: Blade): boolean {
    return this.getSelected().length > 0;
  }
  getSelected(): TagMap[] {
    if (this.tagMaps.length > 0) {
      let filter = this.tagMaps.filter(ref => ref.isChecked)
      return filter == null ? [] : filter;
    }
    return [];
  }
  onSeletedChange(selectedKey: TagMap) {
    this.currentTagMap = selectedKey;
  }
  onItemCheack(event: HTMLInputElement, key: TagMap) {
    key.isChecked = event.checked;
  }
  onAllCheack(event: HTMLInputElement) {
    if (this.tagMaps.length > 0) {
      for (let i = 0; i < this.tagMaps.length; i++) {
        this.tagMaps[i].isChecked = event.checked;
      }
    }
  }


  /**
   * 按照测点名称查询
   * 
   * @param {string} tagName 
   * @memberof TagMapListComponent
   */
  onSearchTagName(names: string) {
    this.isAllChecked = false;
    this.original.forEach(o => o.isChecked = false);
    // names = names.toLowerCase().trim();
    names = names.trim();
    this.tagMaps = [];
    // this.tagMaps = names == "" ? [...this.original]
    //     : [...this.original.filter(o => o.tagName.toLowerCase().startsWith(names))];

    if (names === '') {
      this.isFaultTagChecked = false;
      this.isTagStateMarkChecked = false;
      this.tagMaps = [...this.original]
    } else {
      // this.tagMaps = [...this.original.filter(o => o.tagName.toLowerCase().startsWith(names))];
      this.tagMaps = [...this.original.filter(o => o.tagName.indexOf(names) > -1)];
    }

    this.currentTagMap = null;
    this.canExeEdit();
    this.canDelete();
  }


  /**
   * 按照故障点查询
   * 
   * @memberof TagMapListComponent
   */
  onSearchFaultTag() {
    this.sreachValue = "";
    if (!this.isFaultTagChecked) {
      this.tagMaps = this.original;
      this.tagMaps = this.tagMaps.filter(o => o.faultTag)
    } else {
      // this.tagMaps = [...this.original]     
      if (this.isTagStateMarkChecked == true) {
        this.tagMaps = this.original.filter(o => o.tagstateMark)
      }
      if (this.isTagStateMarkChecked == false) {
        this.tagMaps = [...this.original]

      }
    }
  }


  /**
   * 按照是否有状态标识查询
   * 
   * @memberof TagMapListComponent
   */
  onSearchTagStateMark() {
    this.sreachValue = "";
    if (!this.isTagStateMarkChecked) {
      this.tagMaps = this.original;
      this.tagMaps = this.tagMaps.filter(o => o.tagstateMark)
    } else {
      // this.tagMaps = [...this.original]

      if (this.isFaultTagChecked == true) {
        this.tagMaps = this.original.filter(o => o.faultTag)

      }
      if (this.isFaultTagChecked == false) {
        this.tagMaps = [...this.original]

      }
    }

  }
}




// WEBPACK FOOTER //
// ./src/app/module/basic/model/tag-map/tag-map-list/tag-map-list.component.ts